package com.gamebox.view;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;

import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;

import com.gamebox.dao.GameDao;
import com.gamebox.javaBean.Game;
import com.gamebox.javaBean.User;

@SuppressWarnings("serial")
public class UserTable extends AbstractTableModel {

	private String[] columnNames = { "序号","用户名","昵称","分组","玩过游戏数" };
	private ArrayList<ArrayList<String>> records;
	private JTable table = null;

	public UserTable(final ArrayList<User> users) {
		table = new JTable(this);
		init(users);
		table.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
	            if(e.getClickCount() ==2) {
	            	int i = UserTable.this.table.getSelectedRow();
	            	User user = users.get(i);
	            	new UserDetailDialog(user);
	            }
	        }
		});
	}
	public void update(final ArrayList<User> users){
		table = new JTable(this);
		init(users);
		table.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
	            if(e.getClickCount() ==2) {
	            	int i = UserTable.this.table.getSelectedRow();
	            	User user = users.get(i);
	            	new UserDetailDialog(user);
	            }
	        }
		});
	}
	private void init(ArrayList<User> users) {
		GameDao gameDao = new GameDao();
		records = new ArrayList<ArrayList<String>>();
		for (int i = 0; i < users.size(); i++) {
			User user = users.get(i);
			ArrayList<String> record = new ArrayList<String>();
			record.add(user.getId()+"");
			record.add(user.getName());
			record.add(user.getNickName());
			int gid = user.getGroupId();
			record.add(gameDao.getNameByGId(gid));
			record.add(gameDao.getGameNum(user.getId())+"");
			records.add(record);
		}
	}

	@Override
	public int getRowCount() {
		return records.size();
	}

	@Override
	public int getColumnCount() {
		return columnNames.length;
	}

	@Override
	public Object getValueAt(int rowIndex, int columnIndex) {

		return records.get(rowIndex).get(columnIndex);

	}

	public String getColumnName(int col) {
		return columnNames[col];
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public Class getColumnClass(int c) {
		return getValueAt(0, c).getClass();
	}

	public JTable getTable() {
		return table;
	}

	public void setTable(JTable table) {
		this.table = table;
	}

}
